package com.example.mycommunity.provider;

import com.alibaba.fastjson.JSON;
import com.example.mycommunity.dto.AccessTokenDTO;
import com.example.mycommunity.dto.GiteeUser;
import com.example.mycommunity.dto.GithubUser;
import okhttp3.*;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class GiteeProvider {
    public String getAccessToken(AccessTokenDTO accessTokenDTO){
        MediaType mediaType = MediaType.get("application/json; charset=utf-8");
        OkHttpClient client = new OkHttpClient();

        RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(accessTokenDTO));
        Request request = new Request.Builder()
                .url("https://gitee.com/oauth/token?grant_type=authorization_code&code=" + accessTokenDTO.getCode() + "&client_id=e905751d43aa59d3ce30f7dfe45932a78c629b36143a8c7a2af03fdd2baf344a" +
                        "&redirect_uri=http://localhost:8887/callback&client_secret=64a69aebc67f369a6191c02b14bb6dabb7e7a9930325021049dcc77c1ee39e8a")
                .post(body)
                .build();

        try(Response response = client.newCall(request).execute()) {
            String string = response.body().string();
            System.out.println(string);
            String token = string.split("&")[0].split("=")[1];
            System.out.println(token);
            return token;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public GiteeUser getUser(String accessToken){
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("https://gitee.com/api/v5/user?access_token="+accessToken)
                .build();

        try {
            Response response = client.newCall(request).execute();
            String string = response.body().string();
            System.out.println(string);

            GiteeUser giteeUser = JSON.parseObject(string, GiteeUser.class);
            return giteeUser;
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("返回 null");
        return null;
    }
}
